package top.scauwlt.registry.nacos;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import top.scauwlt.config.RpcConfig;
import top.scauwlt.enums.RpcErrorMessageEnum;
import top.scauwlt.exception.RpcException;
import top.scauwlt.extension.ExtensionLoader;
import top.scauwlt.loadbalance.LoadBalance;
import top.scauwlt.registry.ServiceDiscovery;
import top.scauwlt.registry.nacos.util.NacosUtil;
import top.scauwlt.registry.zk.util.CuratorUtils;
import top.scauwlt.remoting.dto.RpcRequest;
import top.scauwlt.utils.CollectionUtil;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @Author wmm
 * @Date 2022/7/28 16:00
 */
@Slf4j
public class NacosServiceDiscoveryImpl implements ServiceDiscovery {

    private final LoadBalance loadBalance;

    public NacosServiceDiscoveryImpl() {
        loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RpcConfig.getInstance().getLoadBalanceAlgorithm());
    }

    @Override
    public InetSocketAddress lookupService(RpcRequest rpcRequest) {
        String rpcServiceName = rpcRequest.getRpcServiceName();
        List<String> serviceUrlList = NacosUtil.getAllInstance(rpcServiceName);
        log.debug("urls: {}", serviceUrlList);
        if (CollectionUtil.isEmpty(serviceUrlList)) {
            throw new RpcException(RpcErrorMessageEnum.SERVICE_CAN_NOT_BE_FOUND, rpcServiceName);
        }
        String url = loadBalance.selectServiceAddress(serviceUrlList, rpcRequest);
        log.info("Successfully found the service address:[{}]", url);
        String[] socketAddressArray = url.split(":");
        String host = socketAddressArray[0];
        int port = Integer.parseInt(socketAddressArray[1]);
        return new InetSocketAddress(host, port);
    }
}
